#include"kernel/types.h"
#include"kernel/fcntl.h"
#include"user/user.h"
#define MAXPRIME 35
#define MINFACTOR 2
int main(){
	//int temp=0;
	int fpid=0;
	//int pipe_=0;
	int i,primeCandidate=1;
	//int readResult=0;
	int fd[2];
	//pipe_=
	pipe(fd);
	//printf("pipe>>%d\n",pipe_);
	if(0){
		printf("pipe error!\n");
		exit(1);
	};
	write(fd[1],(void*)&primeCandidate,1);
	close(fd[1]);
	if(fpid<0){
		printf("fork error!\n");
		exit(1);
	}
	else {
		while(fpid==0){
			//printf("\n\nWaiting to read...\n");
			read(fd[0],(void*)&primeCandidate,1);
			//printf("ReadResult>>%d\n",readResult);
			//printf("number got:%d\n",primeCandidate);
			while(read(fd[0],(void*)&primeCandidate,1));
			while(1){
				primeCandidate++;
				if(primeCandidate>=MAXPRIME)
					exit(0);
				else;
				
				for(i=MINFACTOR;i<=primeCandidate;i++){
					if(primeCandidate%i==0){
						//printf("found a factor\n");
						break;
					}
					else;
				}
				if(i!=primeCandidate)
					//printf("%d is not a prime\n",primeCandidate)
					;				
				else
					break;			
			}
        		//printf("found a prime :");
        		//printf("%d",primeCandidate);
        		//printf("\n");
        		printf("prime %d \n",primeCandidate);
        		if(primeCandidate==MAXPRIME)
        			exit(0);
        		else{
        			//printf("Creating a child process");
        			//read(0,(void*)&temp,1);
        			//printf("\n");
        			//printf("copying data...\n");
        			write(fd[1],(void*)&primeCandidate,1);
        			fpid=fork();
        			close(fd[1]);
        		}		
		}
		//printf("copied\n");	
		//printf("pipe closed");
		while(wait(0)!=fpid);
		exit(0);
	}
}
